package bingo.jetty;

import java.io.File;

import net.bingosoft.common.config.Config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;
/**
 * Sep 17, 2008 12:39:23 PM
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:内嵌的Jetty 服务器,能够快速启动和关闭,可以加速web应用的开发和调试
 * ChangeLog:
 */
public class EmbeddedJetty{
	private static final Log log = LogFactory.getLog(EmbeddedJetty.class);
	private static int JETTY_CONNECTOR_PORT = Config.getInt("JETTY_CONNECTOR_PORT",8080);
	private static String JETTY_WEB_ROOT = Config.getString("JETTY_WEB_ROOT","WebRoot");
	/**
	 * 获取默认的上下文,即项目的名称
	 * @return
	 */
	public static String getDefaultContext(){
		String DEFAULT_CTXPATH =  Config.getString("DEFAULT_CTXPATH");
		if(DEFAULT_CTXPATH == null){
			DEFAULT_CTXPATH = new File("").getAbsolutePath();
			DEFAULT_CTXPATH = "/" + DEFAULT_CTXPATH.substring(DEFAULT_CTXPATH.lastIndexOf('\\')+1);
		}
		return DEFAULT_CTXPATH;
	}
	/**
	 * 启动内嵌的Jetty
	 * @throws Exception 
	 * @throws Exception
	 */
	public static void startServer() throws Exception  {
		startServer(null,null);
	}
	
	/**
	 * 启动内嵌的Jetty 服务器,可以指定web应用的根路径和上下文路径
	 * @param webRoot web应用的根路径
	 * @param contextPath web应用的上下文路径
	 * @throws Exception
	 */
	public static void startServer(String webRoot,String contextPath) throws Exception{
		Server server = new Server();
		Connector connector = new SelectChannelConnector();
		connector.setPort(JETTY_CONNECTOR_PORT);
		server.setConnectors(new Connector[] { connector });
		if(webRoot == null ) webRoot = JETTY_WEB_ROOT;
		if(contextPath == null) contextPath = getDefaultContext();
		WebAppContext webapp = new WebAppContext(webRoot, contextPath);
		server.addHandler(webapp);
		server.start();
		log.info("EmbeddedJetty started,Explorer is opening ...");
		String projectURL = "http://localhost:" + ((JETTY_CONNECTOR_PORT == 80)? "":JETTY_CONNECTOR_PORT ) + contextPath;
		//调用动态链接库打开浏览器			
		String os = System.getProperty("os.name");
		if(os != null && os.startsWith("Windows")){
			try{
				//调用动态连接库,打开浏览器
				Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + projectURL );
			}catch(Exception ex){
				//忽略打开浏览器的错误,如果打不开,让用户输入地址打开
				log.debug("请在地址栏输入 [ "  +projectURL + " ]访问您的应用...");
			}
		}
		server.join();
		
	}
	
	public static void main(String[] args) throws Exception {
		startServer();
	}
}
